#!/usr/bin/env python3
"""
多样本位置检验MCP服务器 - 大样本近似检验版本

本服务提供以下非参数统计检验方法：
1. Kruskal-Wallis秩和检验 - 检验多个独立样本是否来自相同分布的总体
2. Jonckheere-Terpstra检验 - 检验多个有序组之间是否存在单调趋势
3. Friedman秩和检验 - 检验配对设计中多个处理的效应是否相同
4. Kendall协同系数检验 - 检验多个评价者对同一组对象评价的一致性
5. Cochran Q检验 - 检验配对设计中多个二分类处理的效应是否相同
6. Page趋势检验 - 检验配对设计中多个有序处理是否存在单调趋势
7. Durbin检验 - 用于不完全区组设计中检验多个处理效应是否相同

所有检验均为大样本近似版本（总样本量 > 30）
"""

import asyncio
import json
import sys
from typing import Any, Dict, List, Optional, Union
import numpy as np
from scipy import stats
from scipy.stats import chi2, norm
import warnings
warnings.filterwarnings('ignore')

# MCP相关导入
try:
    from mcp.server.models import InitializationOptions
    from mcp.server import NotificationOptions, Server
    from mcp.types import Resource, Tool, TextContent, ImageContent, EmbeddedResource
except ImportError:
    print("请安装mcp包: pip install mcp")
    sys.exit(1)

server = Server("multi-sample-approximation-tests")

class MultiSampleApproximationTests:
    """多样本位置检验类 - 大样本近似版本"""
    
    @staticmethod
    def _validate_sample_size(data_groups: List[List[float]], min_total_size: int = 30) -> bool:
        """验证总样本量是否满足大样本要求"""
        total_size = sum(len(group) for group in data_groups)
        return total_size > min_total_size
    
    @staticmethod
    def _validate_matrix_size(data_matrix: List[List[float]], min_total_size: int = 30) -> bool:
        """验证矩阵数据总样本量是否满足大样本要求"""
        total_size = len(data_matrix) * len(data_matrix[0]) if data_matrix else 0
        return total_size > min_total_size

    @staticmethod
    def kruskal_wallis_approximation(data_groups: List[List[float]], alpha: float = 0.05) -> Dict[str, Any]:
        """
        Kruskal-Wallis秩和检验（大样本近似版本）
        
        适用条件：
        - 多个独立样本（≥3组）
        - 总样本量 > 30
        - 数据为连续型或有序分类数据
        
        作用：检验多个独立样本是否来自相同分布的总体
        """
        if len(data_groups) < 3:
            raise ValueError("Kruskal-Wallis检验至少需要3组数据")
        
        if not MultiSampleApproximationTests._validate_sample_size(data_groups):
            raise ValueError("总样本量必须大于30才能使用大样本近似")
        
        # 合并所有数据并计算秩
        all_data = []
        group_labels = []
        for i, group in enumerate(data_groups):
            all_data.extend(group)
            group_labels.extend([i] * len(group))
        
        # 计算秩
        ranks = stats.rankdata(all_data)
        
        # 计算各组秩和
        k = len(data_groups)
        n = len(all_data)
        rank_sums = []
        group_sizes = []
        
        for i in range(k):
            group_ranks = [ranks[j] for j, label in enumerate(group_labels) if label == i]
            rank_sums.append(sum(group_ranks))
            group_sizes.append(len(group_ranks))
        
        # 计算H统计量
        H = 12 / (n * (n + 1)) * sum(R**2 / n_i for R, n_i in zip(rank_sums, group_sizes)) - 3 * (n + 1)
        
        # 自由度
        df = k - 1
        
        # 计算p值（卡方近似）
        p_value = 1 - chi2.cdf(H, df)
        
        # 判断结果
        reject_null = p_value < alpha
        
        return {
            "test_name": "Kruskal-Wallis秩和检验（大样本近似）",
            "statistic": float(H),
            "p_value": float(p_value),
            "degrees_of_freedom": int(df),
            "alpha": float(alpha),
            "reject_null_hypothesis": bool(reject_null),
            "conclusion": "拒绝原假设：各组分布不同" if reject_null else "接受原假设：各组分布相同",
            "group_sizes": [int(x) for x in group_sizes],
            "total_sample_size": int(n),
            "rank_sums": [float(x) for x in rank_sums]
        }

    @staticmethod
    def jonckheere_terpstra_approximation(data_groups: List[List[float]], alpha: float = 0.05) -> Dict[str, Any]:
        """
        Jonckheere-Terpstra趋势检验（大样本近似版本）
        
        适用条件：
        - 多个有序独立样本（≥3组）
        - 总样本量 > 30
        - 组间具有自然顺序
        
        作用：检验多个有序组之间是否存在单调趋势
        """
        if len(data_groups) < 3:
            raise ValueError("Jonckheere-Terpstra检验至少需要3组数据")
        
        if not MultiSampleApproximationTests._validate_sample_size(data_groups):
            raise ValueError("总样本量必须大于30才能使用大样本近似")
        
        k = len(data_groups)
        group_sizes = [len(group) for group in data_groups]
        n = sum(group_sizes)
        
        # 计算J统计量
        J = 0
        for i in range(k):
            for j in range(i + 1, k):
                for x in data_groups[i]:
                    for y in data_groups[j]:
                        if x < y:
                            J += 1
                        elif x == y:
                            J += 0.5
        
        # 计算期望值和方差
        E_J = sum(group_sizes[i] * sum(group_sizes[j] for j in range(i + 1, k)) 
                 for i in range(k - 1)) / 2
        
        # 简化的方差计算（大样本近似）
        Var_J = (n * (n - 1) * (2 * n + 5) - sum(ni * (ni - 1) * (2 * ni + 5) for ni in group_sizes)) / 72
        
        # 标准化统计量
        if Var_J > 0:
            Z = (J - E_J) / np.sqrt(Var_J)
        else:
            Z = 0
        
        # 计算p值（双侧检验）
        p_value = 2 * (1 - norm.cdf(abs(Z)))
        
        # 判断结果
        reject_null = p_value < alpha
        
        return {
            "test_name": "Jonckheere-Terpstra趋势检验（大样本近似）",
            "statistic": float(J),
            "standardized_statistic": float(Z),
            "p_value": float(p_value),
            "alpha": float(alpha),
            "reject_null_hypothesis": bool(reject_null),
            "conclusion": "拒绝原假设：存在单调趋势" if reject_null else "接受原假设：不存在单调趋势",
            "group_sizes": [int(x) for x in group_sizes],
            "total_sample_size": int(n),
            "expected_J": float(E_J),
            "variance_J": float(Var_J)
        }

    @staticmethod
    def friedman_approximation(data_matrix: List[List[float]], alpha: float = 0.05) -> Dict[str, Any]:
        """
        Friedman秩和检验（大样本近似版本）
        
        适用条件：
        - 配对设计数据（每行为一个受试者，每列为一个处理）
        - 总样本量 > 30
        - 至少3个处理
        
        作用：检验配对设计中多个处理的效应是否相同
        """
        if not data_matrix or len(data_matrix[0]) < 3:
            raise ValueError("Friedman检验至少需要3个处理")
        
        if not MultiSampleApproximationTests._validate_matrix_size(data_matrix):
            raise ValueError("总样本量必须大于30才能使用大样本近似")
        
        n = len(data_matrix)  # 受试者数量
        k = len(data_matrix[0])  # 处理数量
        
        # 对每行进行排秩
        rank_matrix = []
        for row in data_matrix:
            ranks = stats.rankdata(row)
            rank_matrix.append(ranks)
        
        # 计算各处理的秩和
        rank_sums = [sum(rank_matrix[i][j] for i in range(n)) for j in range(k)]
        
        # 计算Friedman统计量
        Q = 12 / (n * k * (k + 1)) * sum(R**2 for R in rank_sums) - 3 * n * (k + 1)
        
        # 自由度
        df = k - 1
        
        # 计算p值（卡方近似）
        p_value = 1 - chi2.cdf(Q, df)
        
        # 判断结果
        reject_null = p_value < alpha
        
        return {
            "test_name": "Friedman秩和检验（大样本近似）",
            "statistic": float(Q),
            "p_value": float(p_value),
            "degrees_of_freedom": int(df),
            "alpha": float(alpha),
            "reject_null_hypothesis": bool(reject_null),
            "conclusion": "拒绝原假设：处理效应不同" if reject_null else "接受原假设：处理效应相同",
            "subjects": int(n),
            "treatments": int(k),
            "total_sample_size": int(n * k),
            "rank_sums": [float(x) for x in rank_sums]
        }

    @staticmethod
    def kendall_coefficient_concordance(data_matrix: List[List[float]], alpha: float = 0.05) -> Dict[str, Any]:
        """
        Kendall协同系数检验（大样本近似版本）
        
        适用条件：
        - 多个评价者对同一组对象的评价数据
        - 总样本量 > 30
        - 至少3个对象和3个评价者
        
        作用：检验多个评价者对同一组对象评价的一致性
        """
        if not data_matrix or len(data_matrix) < 3 or len(data_matrix[0]) < 3:
            raise ValueError("Kendall协同系数检验至少需要3个对象和3个评价者")
        
        if not MultiSampleApproximationTests._validate_matrix_size(data_matrix):
            raise ValueError("总样本量必须大于30才能使用大样本近似")
        
        n = len(data_matrix)  # 对象数量
        m = len(data_matrix[0])  # 评价者数量
        
        # 对每列（评价者）进行排秩
        rank_matrix = []
        for i in range(n):
            rank_matrix.append([])
        
        for j in range(m):
            column = [data_matrix[i][j] for i in range(n)]
            ranks = stats.rankdata(column)
            for i in range(n):
                rank_matrix[i].append(ranks[i])
        
        # 计算各对象的秩和
        rank_sums = [sum(row) for row in rank_matrix]
        
        # 计算协同系数W
        mean_rank_sum = sum(rank_sums) / n
        S = sum((R - mean_rank_sum)**2 for R in rank_sums)
        W = 12 * S / (m**2 * (n**3 - n))
        
        # 计算卡方统计量
        chi_square = m * (n - 1) * W
        df = n - 1
        
        # 计算p值
        p_value = 1 - chi2.cdf(chi_square, df)
        
        # 判断结果
        reject_null = p_value < alpha
        
        return {
            "test_name": "Kendall协同系数检验（大样本近似）",
            "concordance_coefficient": float(W),
            "chi_square_statistic": float(chi_square),
            "p_value": float(p_value),
            "degrees_of_freedom": int(df),
            "alpha": float(alpha),
            "reject_null_hypothesis": bool(reject_null),
            "conclusion": "拒绝原假设：评价者间存在一致性" if reject_null else "接受原假设：评价者间无一致性",
            "objects": int(n),
            "raters": int(m),
            "total_sample_size": int(n * m),
            "rank_sums": [float(x) for x in rank_sums]
        }

    @staticmethod
    def cochran_q_test(data_matrix: List[List[int]], alpha: float = 0.05) -> Dict[str, Any]:
        """
        Cochran Q检验（大样本近似版本）
        
        适用条件：
        - 配对设计的二分类数据（0或1）
        - 总样本量 > 30
        - 至少3个处理
        
        作用：检验配对设计中多个二分类处理的效应是否相同
        """
        if not data_matrix or len(data_matrix[0]) < 3:
            raise ValueError("Cochran Q检验至少需要3个处理")
        
        if not MultiSampleApproximationTests._validate_matrix_size(data_matrix):
            raise ValueError("总样本量必须大于30才能使用大样本近似")
        
        # 验证数据为二分类
        for row in data_matrix:
            for val in row:
                if val not in [0, 1]:
                    raise ValueError("Cochran Q检验要求数据为二分类（0或1）")
        
        n = len(data_matrix)  # 受试者数量
        k = len(data_matrix[0])  # 处理数量
        
        # 计算各处理的成功次数
        treatment_sums = [sum(data_matrix[i][j] for i in range(n)) for j in range(k)]
        
        # 计算各受试者的成功次数
        subject_sums = [sum(row) for row in data_matrix]
        
        # 计算Q统计量
        G = sum(treatment_sums)
        Q = (k - 1) * (k * sum(T**2 for T in treatment_sums) - G**2) / (k * G - sum(s**2 for s in subject_sums))
        
        # 自由度
        df = k - 1
        
        # 计算p值（卡方近似）
        p_value = 1 - chi2.cdf(Q, df)
        
        # 判断结果
        reject_null = p_value < alpha
        
        return {
            "test_name": "Cochran Q检验（大样本近似）",
            "statistic": float(Q),
            "p_value": float(p_value),
            "degrees_of_freedom": int(df),
            "alpha": float(alpha),
            "reject_null_hypothesis": bool(reject_null),
            "conclusion": "拒绝原假设：处理效应不同" if reject_null else "接受原假设：处理效应相同",
            "subjects": int(n),
            "treatments": int(k),
            "total_sample_size": int(n * k),
            "treatment_sums": [int(x) for x in treatment_sums],
            "total_successes": int(G)
        }

    @staticmethod
    def page_test(data_matrix: List[List[float]], alpha: float = 0.05) -> Dict[str, Any]:
        """
        Page趋势检验（大样本近似版本）
        
        适用条件：
        - 配对设计数据，处理间有预期的顺序
        - 总样本量 > 30
        - 至少3个有序处理
        
        作用：检验配对设计中多个有序处理是否存在单调趋势
        """
        if not data_matrix or len(data_matrix[0]) < 3:
            raise ValueError("Page检验至少需要3个处理")
        
        if not MultiSampleApproximationTests._validate_matrix_size(data_matrix):
            raise ValueError("总样本量必须大于30才能使用大样本近似")
        
        n = len(data_matrix)  # 受试者数量
        k = len(data_matrix[0])  # 处理数量
        
        # 对每行进行排秩
        rank_matrix = []
        for row in data_matrix:
            ranks = stats.rankdata(row)
            rank_matrix.append(ranks)
        
        # 计算Page统计量L
        weights = list(range(1, k + 1))  # 权重：1, 2, 3, ..., k
        L = sum(weights[j] * sum(rank_matrix[i][j] for i in range(n)) for j in range(k))
        
        # 计算期望值和方差
        E_L = n * k * (k + 1)**2 / 4
        Var_L = n * k**2 * (k + 1) * (k - 1) / 144
        
        # 标准化统计量
        if Var_L > 0:
            Z = (L - E_L) / np.sqrt(Var_L)
        else:
            Z = 0
        
        # 计算p值（单侧检验，检验递增趋势）
        p_value = 1 - norm.cdf(Z)
        
        # 判断结果
        reject_null = p_value < alpha
        
        return {
            "test_name": "Page趋势检验（大样本近似）",
            "statistic": float(L),
            "standardized_statistic": float(Z),
            "p_value": float(p_value),
            "alpha": float(alpha),
            "reject_null_hypothesis": bool(reject_null),
            "conclusion": "拒绝原假设：存在递增趋势" if reject_null else "接受原假设：不存在递增趋势",
            "subjects": int(n),
            "treatments": int(k),
            "total_sample_size": int(n * k),
            "expected_L": float(E_L),
            "variance_L": float(Var_L)
        }

    @staticmethod
    def durbin_test(data_matrix: List[List[Optional[float]]], alpha: float = 0.05) -> Dict[str, Any]:
        """
        Durbin检验（大样本近似版本）
        
        适用条件：
        - 不完全区组设计（允许缺失值）
        - 总样本量 > 30
        - 至少3个处理
        
        作用：用于不完全区组设计中检验多个处理效应是否相同
        """
        if not data_matrix or len(data_matrix[0]) < 3:
            raise ValueError("Durbin检验至少需要3个处理")
        
        # 计算非缺失值的总数
        total_non_missing = sum(sum(1 for val in row if val is not None) for row in data_matrix)
        if total_non_missing <= 30:
            raise ValueError("总样本量必须大于30才能使用大样本近似")
        
        n = len(data_matrix)  # 区组数量
        k = len(data_matrix[0])  # 处理数量
        
        # 对每行的非缺失值进行排秩
        rank_matrix = []
        for row in data_matrix:
            # 提取非缺失值及其位置
            non_missing = [(val, idx) for idx, val in enumerate(row) if val is not None]
            if len(non_missing) < 2:
                rank_matrix.append([None] * k)
                continue
            
            # 排秩
            values = [val for val, _ in non_missing]
            ranks = stats.rankdata(values)
            
            # 构建完整的秩向量
            row_ranks = [None] * k
            for (val, idx), rank in zip(non_missing, ranks):
                row_ranks[idx] = rank
            rank_matrix.append(row_ranks)
        
        # 计算各处理的秩和和观测次数
        treatment_rank_sums = []
        treatment_counts = []
        
        for j in range(k):
            ranks = [rank_matrix[i][j] for i in range(n) if rank_matrix[i][j] is not None]
            treatment_rank_sums.append(sum(ranks))
            treatment_counts.append(len(ranks))
        
        # 计算Durbin统计量
        # 简化版本的Durbin统计量计算
        total_ranks = sum(treatment_rank_sums)
        expected_rank_sums = [count * (total_ranks / sum(treatment_counts)) for count in treatment_counts]
        
        T = sum((R - E)**2 / E for R, E in zip(treatment_rank_sums, expected_rank_sums) if E > 0)
        
        # 自由度
        df = k - 1
        
        # 计算p值（卡方近似）
        p_value = 1 - chi2.cdf(T, df)
        
        # 判断结果
        reject_null = p_value < alpha
        
        return {
            "test_name": "Durbin检验（大样本近似）",
            "statistic": float(T),
            "p_value": float(p_value),
            "degrees_of_freedom": int(df),
            "alpha": float(alpha),
            "reject_null_hypothesis": bool(reject_null),
            "conclusion": "拒绝原假设：处理效应不同" if reject_null else "接受原假设：处理效应相同",
            "blocks": int(n),
            "treatments": int(k),
            "total_observations": int(total_non_missing),
            "treatment_rank_sums": [float(x) for x in treatment_rank_sums],
            "treatment_counts": [int(x) for x in treatment_counts]
        }

    @staticmethod
    def auto_select_test(data_groups: Optional[List[List[float]]] = None,
                        data_matrix: Optional[List[List[Union[float, int, None]]]] = None,
                        design_type: str = "independent",
                        data_type: str = "continuous",
                        has_order: bool = False,
                        alpha: float = 0.05) -> Dict[str, Any]:
        """
        自动选择合适的多样本位置检验方法
        
        参数：
        - data_groups: 独立样本数据组（用于独立设计）
        - data_matrix: 配对数据矩阵（用于配对设计）
        - design_type: 设计类型 ("independent", "paired", "incomplete_block")
        - data_type: 数据类型 ("continuous", "binary")
        - has_order: 是否具有自然顺序
        - alpha: 显著性水平
        """
        try:
            if design_type == "independent":
                if data_groups is None:
                    raise ValueError("独立设计需要提供data_groups")
                
                if has_order:
                    return MultiSampleApproximationTests.jonckheere_terpstra_approximation(data_groups, alpha)
                else:
                    return MultiSampleApproximationTests.kruskal_wallis_approximation(data_groups, alpha)
            
            elif design_type == "paired":
                if data_matrix is None:
                    raise ValueError("配对设计需要提供data_matrix")
                
                if data_type == "binary":
                    # 转换为整数矩阵
                    binary_matrix = [[int(val) if val is not None else val for val in row] for row in data_matrix]
                    return MultiSampleApproximationTests.cochran_q_test(binary_matrix, alpha)
                elif has_order:
                    return MultiSampleApproximationTests.page_test(data_matrix, alpha)
                else:
                    return MultiSampleApproximationTests.friedman_approximation(data_matrix, alpha)
            
            elif design_type == "incomplete_block":
                if data_matrix is None:
                    raise ValueError("不完全区组设计需要提供data_matrix")
                return MultiSampleApproximationTests.durbin_test(data_matrix, alpha)
            
            else:
                raise ValueError(f"不支持的设计类型: {design_type}")
        
        except Exception as e:
            return {
                "error": str(e),
                "recommendation": "请检查数据格式和参数设置"
            }

# MCP工具定义
@server.list_tools()
async def handle_list_tools() -> list[Tool]:
    """列出所有可用的工具"""
    return [
        Tool(
            name="kruskal_wallis_approximation",
            description="Kruskal-Wallis秩和检验（大样本近似版本）- 用于检验多个独立样本是否来自相同分布的总体",
            inputSchema={
                "type": "object",
                "properties": {
                    "data_groups": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {"type": "number"}
                        },
                        "description": "多组独立样本数据，每组为一个数值列表"
                    },
                    "alpha": {
                        "type": "number",
                        "default": 0.05,
                        "description": "显著性水平"
                    }
                },
                "required": ["data_groups"]
            }
        ),
        Tool(
            name="jonckheere_terpstra_approximation",
            description="Jonckheere-Terpstra趋势检验（大样本近似版本）- 用于检验多个有序组之间是否存在单调趋势",
            inputSchema={
                "type": "object",
                "properties": {
                    "data_groups": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {"type": "number"}
                        },
                        "description": "按顺序排列的多组数据，每组为一个数值列表"
                    },
                    "alpha": {
                        "type": "number",
                        "default": 0.05,
                        "description": "显著性水平"
                    }
                },
                "required": ["data_groups"]
            }
        ),
        Tool(
            name="friedman_approximation",
            description="Friedman秩和检验（大样本近似版本）- 用于检验配对设计中多个处理的效应是否相同",
            inputSchema={
                "type": "object",
                "properties": {
                    "data_matrix": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {"type": "number"}
                        },
                        "description": "配对数据矩阵，每行为一个受试者，每列为一个处理"
                    },
                    "alpha": {
                        "type": "number",
                        "default": 0.05,
                        "description": "显著性水平"
                    }
                },
                "required": ["data_matrix"]
            }
        ),
        Tool(
            name="kendall_coefficient_concordance",
            description="Kendall协同系数检验（大样本近似版本）- 用于检验多个评价者对同一组对象评价的一致性",
            inputSchema={
                "type": "object",
                "properties": {
                    "data_matrix": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {"type": "number"}
                        },
                        "description": "评价数据矩阵，每行为一个对象，每列为一个评价者"
                    },
                    "alpha": {
                        "type": "number",
                        "default": 0.05,
                        "description": "显著性水平"
                    }
                },
                "required": ["data_matrix"]
            }
        ),
        Tool(
            name="cochran_q_test",
            description="Cochran Q检验（大样本近似版本）- 用于检验配对设计中多个二分类处理的效应是否相同",
            inputSchema={
                "type": "object",
                "properties": {
                    "data_matrix": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {
                                "type": "integer",
                                "minimum": 0,
                                "maximum": 1
                            }
                        },
                        "description": "二分类数据矩阵，每行为一个受试者，每列为一个处理（0或1）"
                    },
                    "alpha": {
                        "type": "number",
                        "default": 0.05,
                        "description": "显著性水平"
                    }
                },
                "required": ["data_matrix"]
            }
        ),
        Tool(
            name="page_test",
            description="Page趋势检验（大样本近似版本）- 用于检验配对设计中多个有序处理是否存在单调趋势",
            inputSchema={
                "type": "object",
                "properties": {
                    "data_matrix": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {"type": "number"}
                        },
                        "description": "配对数据矩阵，每行为一个受试者，每列为一个有序处理"
                    },
                    "alpha": {
                        "type": "number",
                        "default": 0.05,
                        "description": "显著性水平"
                    }
                },
                "required": ["data_matrix"]
            }
        ),
        Tool(
            name="durbin_test",
            description="Durbin检验（大样本近似版本）- 用于不完全区组设计中检验多个处理效应是否相同",
            inputSchema={
                "type": "object",
                "properties": {
                    "data_matrix": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {
                                "type": ["number", "null"]
                            }
                        },
                        "description": "数据矩阵，缺失值用null表示"
                    },
                    "alpha": {
                        "type": "number",
                        "default": 0.05,
                        "description": "显著性水平"
                    }
                },
                "required": ["data_matrix"]
            }
        ),
        Tool(
            name="auto_select_test",
            description="自动选择合适的多样本位置检验方法",
            inputSchema={
                "type": "object",
                "properties": {
                    "data_groups": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {"type": "number"}
                        },
                        "description": "独立样本数据组（用于独立设计）"
                    },
                    "data_matrix": {
                        "type": "array",
                        "items": {
                            "type": "array",
                            "items": {
                                "type": ["number", "integer"]
                            }
                        },
                        "description": "配对数据矩阵（用于配对设计）"
                    },
                    "design_type": {
                        "type": "string",
                        "enum": ["independent", "paired", "incomplete_block"],
                        "default": "independent",
                        "description": "设计类型"
                    },
                    "data_type": {
                        "type": "string",
                        "enum": ["continuous", "binary"],
                        "default": "continuous",
                        "description": "数据类型"
                    },
                    "has_order": {
                        "type": "boolean",
                        "default": False,
                        "description": "是否具有自然顺序"
                    },
                    "alpha": {
                        "type": "number",
                        "default": 0.05,
                        "description": "显著性水平"
                    }
                },
                "required": []
            }
        )
    ]

# 工具调用处理器
@server.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list[TextContent]:
    """处理工具调用"""
    try:
        if name == "kruskal_wallis_approximation":
            result = MultiSampleApproximationTests.kruskal_wallis_approximation(
                arguments["data_groups"],
                arguments.get("alpha", 0.05)
            )
        elif name == "jonckheere_terpstra_approximation":
            result = MultiSampleApproximationTests.jonckheere_terpstra_approximation(
                arguments["data_groups"],
                arguments.get("alpha", 0.05)
            )
        elif name == "friedman_approximation":
            result = MultiSampleApproximationTests.friedman_approximation(
                arguments["data_matrix"],
                arguments.get("alpha", 0.05)
            )
        elif name == "kendall_coefficient_concordance":
            result = MultiSampleApproximationTests.kendall_coefficient_concordance(
                arguments["data_matrix"],
                arguments.get("alpha", 0.05)
            )
        elif name == "cochran_q_test":
            result = MultiSampleApproximationTests.cochran_q_test(
                arguments["data_matrix"],
                arguments.get("alpha", 0.05)
            )
        elif name == "page_test":
            result = MultiSampleApproximationTests.page_test(
                arguments["data_matrix"],
                arguments.get("alpha", 0.05)
            )
        elif name == "durbin_test":
            result = MultiSampleApproximationTests.durbin_test(
                arguments["data_matrix"],
                arguments.get("alpha", 0.05)
            )
        elif name == "auto_select_test":
            result = MultiSampleApproximationTests.auto_select_test(
                arguments.get("data_groups"),
                arguments.get("data_matrix"),
                arguments.get("design_type", "independent"),
                arguments.get("data_type", "continuous"),
                arguments.get("has_order", False),
                arguments.get("alpha", 0.05)
            )
        else:
            raise ValueError(f"未知的工具: {name}")
        
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False, indent=2))]
    
    except Exception as e:
        error_result = {
            "error": str(e),
            "tool": name,
            "arguments": arguments
        }
        return [TextContent(type="text", text=json.dumps(error_result, ensure_ascii=False, indent=2))]

async def main():
    """主函数"""
    from mcp.server.stdio import stdio_server
    
    async with stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="multi-sample-approximation-tests",
                server_version="1.0.0",
                capabilities=server.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={},
                ),
            ),
        )

if __name__ == "__main__":
    asyncio.run(main())